#include <QScrollBar>

#include "downloaditem.h"
#include "downloaditemlist.h"

namespace Jcr
{
class DownloadItemListPrivate
{
public:
    DownloadItemListPrivate(DownloadItemList* q);
    void layoutItems();

    QWidget* widget;
    DownloadItemList* q_ptr;
    QList<DownloadItem* > items;
};

DownloadItemListPrivate::DownloadItemListPrivate(DownloadItemList *q) : q_ptr(q)
{
    widget = new QWidget(q);
    widget->setMinimumWidth(150);
    q_ptr->setWidget(widget);
}

void DownloadItemListPrivate::layoutItems()
{
    int y = 0;
    for (int i = 0; i < items.size(); ++i) {
        Jcr::DownloadItem* di = items.at(i);
        di->move(QPoint(0, y));
        di->resize(QSize(q_ptr->width(), di->height()));
        di->show();
        y += di->height();
    }

    widget->setMinimumHeight(y);
}

DownloadItemList::DownloadItemList(QWidget* parent) : QScrollArea(parent)
{
    d_ptr = new DownloadItemListPrivate(this);
    this->setWidgetResizable(true);
}

DownloadItemList::~DownloadItemList()
{
    qDeleteAll(d_ptr->items);
    d_ptr->items.clear();
}

void DownloadItemList::addItem(Jcr::DownloadItem* item)
{
    if (item && !d_ptr->items.contains(item)) {
        item->setParent(d_ptr->widget);
        d_ptr->items.append(item);
        d_ptr->layoutItems();
        scrollToEnd();
    }
}

void DownloadItemList::removeItem(Jcr::DownloadItem* item)
{
    if (d_ptr->items.contains(item)) {
        d_ptr->items.removeAll(item);
        delete item;
        item = nullptr;
        d_ptr->layoutItems();
    }
}

const QList<Jcr::DownloadItem*> DownloadItemList::items() const
{
    return d_ptr->items;
}

void DownloadItemList::clear()
{
    qDeleteAll(d_ptr->items);
    d_ptr->items.clear();
    d_ptr->layoutItems();
}

void DownloadItemList::scrollToEnd()
{
    verticalScrollBar()->setValue(verticalScrollBar()->maximum());
}

void DownloadItemList::scrollToTop()
{
    verticalScrollBar()->setValue(0);
}

void DownloadItemList::showEvent(QShowEvent* e)
{
    d_ptr->layoutItems();
    QScrollArea::showEvent(e);
}

void DownloadItemList::resizeEvent(QResizeEvent *e)
{
    d_ptr->layoutItems();
    QScrollArea::resizeEvent(e);
}


} // namespace jcr
